var http = require('http');
var config = require('../config').mockConfig;

var httpRequest = (requestdata, method, url, callback) => {
    requestdata = JSON.stringify(requestdata);
    console.log(`http request data: ${requestdata}`);

    var options = {
        host: config.MOCK_SERVER_URL,
        headers: {
            'Content-Type': 'application/json;charset=UTF-8',
            'Content-Length': Buffer.byteLength(requestdata)
        },
        path: config.MOCK_BASE_PATH + url,
        method: method
    };

    console.log(`http request options: ${JSON.stringify(options)}`);

    var httpreq = http.request(options, httpres => {
        console.log(`STATUS: ${httpres.statusCode}`);
        console.log(`HEADERS: ${JSON.stringify(httpres.headers)}`);

        var chunks = [];
        var size = 0;
        httpres.on('data', chunk => {
            chunks.push(chunk);
            size += chunk.length;
        });
        httpres.on('end', () => {
            var buf = Buffer.concat(chunks, size);
            var data = buf.toString('utf8');

            try {
                var dataObj = JSON.parse(data);
                callback({
                    resultCode: 0,
                    data: dataObj
                });
            } catch (error) {
                callback({
                    resultCode: 1,
                    data: error.stack
                });
            }
        });
    });

    httpreq.on('error', error => {
        console.log(`http request failed: ${JSON.stringify(error)}`);
        callback({
            resultCode: 1,
            data: error.stack
        });
    });
    httpreq.write(requestdata);
    httpreq.end();
};

module.exports.httpRequest = httpRequest;